<template>
  <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
    <!-- 加载状态提示 -->
    <div v-if="isLoading" class="lg:col-span-2 flex items-center justify-center h-96">
      <div class="flex flex-col items-center">
        <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
        <p class="mt-4 text-gray-300">正在加载文章内容...</p>
      </div>
    </div>

    <!-- 文章内容 -->
    <div class="lg:col-span-2" v-else>
      <article class="bg-dark-light rounded-xl border border-gray-custom overflow-hidden" v-if="post">
        <div class="relative h-64 md:h-96 overflow-hidden">
          <img :src="post.image" :alt="post.title" class="w-full h-full object-cover">
          <div class="absolute inset-0 bg-gradient-to-t from-dark to-transparent"></div>
          <div class="absolute top-4 left-4">
            <span class="bg-primary/90 text-white text-xs font-medium px-2.5 py-0.5 rounded-full">
              {{ post.category }}
            </span>
          </div>
        </div>
        
        <div class="p-6 md:p-8">
          <h1 class="text-2xl md:text-3xl font-bold text-white mb-6 title-h1">{{ post.title }}</h1>
          
          <div class="flex flex-wrap items-center mb-8 text-sm">
            <div class="flex items-center mr-6 mb-2 md:mb-0">
              <img src="https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAJv2GiVbFnfFAxmGO5MMRMgLR8T9ug7AALPFwACnQapVMUxTiHpUbTQNgQ.jpeg" alt="科技创客" class="w-6 h-6 rounded-full mr-2">
              <span class="text-gray-300">{{ post.author }}</span>
            </div>
            <div class="flex items-center mr-6 mb-2 md:mb-0">
              <i class="fa fa-calendar-o text-gray-400 mr-2"></i>
              <time :datetime="post.date" class="text-gray-400">{{ formatDate(post.date) }}</time>
            </div>
            <div class="flex items-center mr-6 mb-2 md:mb-0">
              <i class="fa fa-clock-o text-gray-400 mr-2"></i>
              <span class="text-gray-400">{{ post.readTime }}</span>
            </div>
            <div class="flex items-center mb-2 md:mb-0">
              <i class="fa fa-eye text-gray-400 mr-2"></i>
              <span class="text-gray-400">{{ post.views }} 次浏览</span>
            </div>
          </div>
          
          <div class="prose prose-invert max-w-none text-gray-300 custom-md" v-if="mdContent" v-html="mdContent"></div>
          <div class="prose prose-invert max-w-none text-gray-300 custom-md" v-else v-html="post.content"></div>
          
          <div class="mt-10 pt-6 border-t border-gray-custom">
            <div class="flex flex-wrap gap-2 mb-6">
              <span class="text-gray-400">标签：</span>
              <template v-for="tag in post.tags" :key="tag">
                <router-link :to="`/tag/${tag}`" class="bg-gray-custom/30 hover:bg-primary/80 text-gray-300 hover:text-white px-3 py-1 rounded-full text-sm transition-colors">
                  {{ tag }}
                </router-link>
              </template>
            </div>
            
            <div class="flex justify-between items-center">
              <button class="flex items-center space-x-2 bg-gray-custom/30 hover:bg-gray-custom text-gray-300 px-4 py-2 rounded-lg transition-colors">
                <i class="fa fa-share-alt"></i>
                <span>分享文章</span>
              </button>
              
              <button class="flex items-center space-x-2 bg-gray-custom/30 hover:bg-gray-custom text-gray-300 px-4 py-2 rounded-lg transition-colors">
                <i class="fa fa-bookmark-o"></i>
                <span>收藏</span>
              </button>
            </div>
          </div>
        </div>
      </article>
      
      <!-- 文章不存在提示 -->
      <div v-else class="bg-dark-light rounded-xl border border-gray-custom p-8 text-center">
        <p class="text-gray-400">未找到对应的文章内容</p>
        <router-link to="/" class="mt-4 inline-block text-primary hover:underline">返回首页</router-link>
      </div>
      
      <!-- 相关文章 -->
      <section class="mt-10" v-if="relatedPosts.length > 0">
        <h3 class="text-xl font-bold text-white mb-6">相关文章</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <template v-for="relatedPost in relatedPosts" :key="relatedPost.id">
            <router-link :to="'/post/' + relatedPost.id" class="block group">
              <article class="flex bg-dark-light rounded-xl overflow-hidden border border-gray-custom card-hover group-hover:border-primary transition-colors">
                <div class="w-1/3 flex-shrink-0">
                  <img :src="relatedPost.image" :alt="relatedPost.title" class="w-full h-full object-cover">
                </div>
                <div class="w-2/3 p-4">
                  <h4 class="text-sm font-medium text-white group-hover:text-primary transition-colors line-clamp-2 mb-2">
                    {{ relatedPost.title }}
                  </h4>
                  <time :datetime="relatedPost.date" class="text-gray-500 text-xs">
                    {{ formatDate(relatedPost.date) }}
                  </time>
                </div>
              </article>
            </router-link>
          </template>
        </div>
      </section>
    </div>
    
    <!-- 侧边栏 -->
    <div class="lg:col-span-1">
      <Sidebar />
    </div>
  </div>
</template>

<script>
import Sidebar from '../components/Sidebar.vue'
import blogPosts from '../data/blogPosts'
import { marked } from 'marked'

export default {
  components: {
    Sidebar
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      posts: blogPosts,
      post: null,
      relatedPosts: [],
      mdContent: '',
      isLoading: true, // 加载状态标识
      error: null // 错误信息
    }
  },
  // 路由导航守卫 - 进入路由前
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 预加载指示器
      vm.isLoading = true
    })
  },
  // 路由导航守卫 - 离开路由时
  beforeRouteLeave(to, from, next) {
    // 清理可能的定时器或事件监听
    this.cleanupResources()
    next()
  },
  async mounted() {
    try {
      // 查找对应的文章
      this.post = this.posts.find(post => post.id === parseInt(this.id))
      
      if (this.post) {
        // 加载 markdown 内容（使用动态导入优化）
        const mdModule = await import(`../document/${this.post.id}.md?raw`)
        this.mdContent = marked.parse(mdModule.default || mdModule)
        
        // 查找相关文章（同分类但不同ID）
        this.relatedPosts = this.posts
          .filter(p => p.category === this.post.category && p.id !== this.post.id)
          .slice(0, 2)
      }
    } catch (e) {
      console.error('文章加载失败:', e)
      this.error = '文章内容加载失败，请稍后重试'
      this.mdContent = `<p class="text-red-400">${this.error}</p>`
    } finally {
      // 无论成功失败都关闭加载状态
      this.isLoading = false
    }
  },
  methods: {
    formatDate(dateString) {
      try {
        const date = new Date(dateString)
        return date.toLocaleDateString('zh-CN', { 
          year: 'numeric', 
          month: 'long', 
          day: 'numeric' 
        })
      } catch (e) {
        return dateString // 日期格式错误时返回原始字符串
      }
    },
    // 清理资源方法
    cleanupResources() {
      // 可以在这里清除定时器、事件监听等
      // 例如: clearInterval(this.timer)
    }
  }
}
</script>

<style scoped>
/* 文章详情页特定样式 */
.prose h3 {
  color: #fff;
  font-size: 1.25rem;
  margin-top: 1.5rem;
  margin-bottom: 1rem;
}

.prose p {
  margin-bottom: 1rem;
  line-height: 1.7;
}

/* 加载动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

<style>
.custom-md {
  font-size: 1.1rem;
  line-height: 2;
  color: #e5e7eb;
}
.custom-md h1, .custom-md h2, .custom-md h3, .custom-md h4 {
  color: #fff;
  font-weight: bold;
  margin-top: 2.2em;
  margin-bottom: 1em;
  line-height: 1.3;
}

.custom-md h1 {
  font-size: 2.2rem !important;
  border-bottom: 2px solid #6366f1 !important;
  padding-bottom: 0.3em !important;
  margin-top: 2.5em !important;
  margin-bottom: 1.2em !important;
  color: #fff !important;
  font-weight: 900 !important;
  background: linear-gradient(90deg, #6366f1 0%, #a5b4fc 100%) !important;
  background-clip: text !important;
  -webkit-background-clip: text !important;
  -webkit-text-fill-color: transparent !important;
  text-shadow: 0 6px 32px #6366f199, 0 1px 0 #232946, 0 0 8px #fff8, 0 0 2px #9d9edfcc;
}
.custom-md h2 {
  font-size: 1.7rem;
  border-left: 5px solid #6366f1;
  padding-left: 0.7em;
  background: rgba(99,102,241,0.10);
  border-radius: 0.2em;
  margin-top: 2em;
  margin-bottom: 1em;
  color: #a5b4fc;
  font-weight: 700;
  box-shadow: 0 2px 16px #6366f122;
  position: relative;
}
.custom-md h2::before {
  content: '';
  display: inline-block;
  width: 0.5em;
  height: 0.5em;
  background: #6366f1;
  border-radius: 50%;
  margin-right: 0.5em;
  vertical-align: middle;
}
.custom-md h3 {
  font-size: 1.3rem;
  color: #c7d2fe;
  margin-top: 1.5em;
  margin-bottom: 0.8em;
  font-weight: 600;
  border-left: 3px solid #818cf8;
  padding-left: 0.5em;
  background: rgba(129,140,248,0.08);
}
.custom-md h4 {
  font-size: 1.1rem;
  color: #dbeafe;
  margin-top: 1.2em;
  margin-bottom: 0.7em;
  font-weight: 500;
  border-left: 2px solid #a5b4fc;
  padding-left: 0.4em;
}
.custom-md p {
  margin-bottom: 1.2em;
  text-align: justify;
}
.custom-md ul, .custom-md ol {
  margin-left: 1.5em;
  margin-bottom: 1.2em;
}
.custom-md li {
  margin-bottom: 0.5em;
}
.custom-md blockquote {
  border-left: 4px solid #6366f1;
  background: rgba(99,102,241,0.08);
  color: #a5b4fc;
  padding: 0.7em 1.2em;
  margin: 1.5em 0;
  border-radius: 0.2em;
  font-style: italic;
}
.custom-md code {
  background: #232946;
  color: #facc15;
  padding: 0.2em 0.4em;
  border-radius: 0.2em;
  font-size: 0.98em;
}
.custom-md pre code {
  background: #18181b;
  color: #facc15;
  padding: 1em;
  border-radius: 0.4em;
  display: block;
  font-size: 1em;
  overflow-x: auto;
}
.custom-md hr {
  border: none;
  border-top: 2px dashed #6366f1;
  margin: 2em 0;
}
.custom-md img {
  max-width: 100%;
  border-radius: 0.5em;
  margin: 1.5em 0;
  box-shadow: 0 4px 24px #0003;
}
.custom-md table {
  width: 100%;
  border-collapse: collapse;
  margin: 2em 0;
  background: rgba(36, 40, 56, 0.85);
  border-radius: 0.5em;
  overflow: hidden;
  color: #fff;
  font-size: 1.05em;
  box-shadow: 0 2px 16px #6366f122;
}
.custom-md th, .custom-md td {
  border: 1px solid #6366f1;
  padding: 0.75em 1em;
  text-align: left;
  color: #fff;
}
.custom-md th {
  background: linear-gradient(90deg, #6366f1 0%, #232946 100%);
  color: #fff;
  font-weight: 700;
}
.custom-md tr:nth-child(even) {
  background: rgba(99,102,241,0.08);
}
.custom-md tr:hover {
  background: rgba(99,102,241,0.18);
}
</style>